package com.qf.file.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.qf.file.config.AlibabaOSSConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 30909
 * 对AlibabaOSS进行分装
 */
public class AlibabaOSSUtil {

    /**
     * 配置oss客户端
     */
    private static OSS ossClient = new OSSClientBuilder().build(
            "https://" + AlibabaOSSConfig.END_POINT,
            AlibabaOSSConfig.ACCESS_KEY_ID,
            AlibabaOSSConfig.ACCESS_KEY_SECRET
    );


    /**
     * 如果上传了一个文件，就能由此方法得知文件的url
     * 获取 url 的方法
     *
     * @param fileName
     * @return
     */
    public static String getUrl(String fileName) {
        String uploadUrl = "https://" + AlibabaOSSConfig.BUCKET_NAME + "." +
                AlibabaOSSConfig.END_POINT + "/" + fileName;
        return uploadUrl;
    }

    /**
     * 文件上传的方法
     *
     * @param fileName 文件名
     * @param file     文件本身
     * @return 返回文件名保存的位置
     */
    public static String uploadFile(String fileName, File file) {
        //创建 putObjectRequest
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                AlibabaOSSConfig.BUCKET_NAME, fileName, file);

        //上传文件
        ossClient.putObject(putObjectRequest);
        return getUrl(fileName);
    }

    /**
     * 基于流操作的文件上传
     *
     * @param fileName  文件名
     * @param inputStream   文件数据流
     * @return   返回文件保存的位置的url
     */
    public static String uploadFile(String fileName, InputStream inputStream) {
        //创建 PutObjectRequest
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                AlibabaOSSConfig.BUCKET_NAME, fileName, inputStream);

        // 上传文件
        ossClient.putObject(putObjectRequest);
        return getUrl(fileName);
    }


    /**
     * 上传文件的测试
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String url = uploadFile("aaa.jpg", new FileInputStream("C:\\test\\1.jpg"));

        System.out.println("url = " + url);
    }
}
